# From:
# https://www.cnblogs.com/wxd501/p/17070184.html
# https://github.com/N0I0C0K/TranslaterCollections/blob/master/youdao_translaterV3.py
import base64
import hashlib
import json
import time

import requests
from Crypto.Cipher import AES
from Crypto.Hash import MD5
# import execjs


def _decode(src: str) -> dict:
    key = b'ydsecret://query/key/B*RGygVywfNBwpmBaZg*WT7SIOUP2T0C9WHMZN39j^DAdaZhAnxvGcCY6VYFwnHl'
    iv = b'ydsecret://query/iv/C@lZe2YzHtZ2CYgaXKSVfsb7Y4QWHjITPPZ0nQp87fBeJ!Iv6v^6fvi2WN@bYpJ4'
    cryptor = AES.new(
        MD5.new(key).digest()[:16], AES.MODE_CBC, MD5.new(iv).digest()[:16]
    )
    res = cryptor.decrypt(base64.urlsafe_b64decode(src))
    txt = res.decode('utf-8')
    # return json.loads(txt[: txt.rindex("}") + 1])
    # return txt
    # d = json.loads(txt)
    d = json.loads(txt[: txt.rindex('}') + 1])
    main = d['translateResult'][0][0]['tgt']

    try:
        addition = d['dictResult']['ce']['word']['trs'][0]['#tran']
    except:
            addition = d['dictResult']['ec']['word']['trs'][0]['tran']
    return f'{main}\r\n\r\n{addition}'


def translate(source_text: str):
    localtime = str(int(time.time() * 1000))
    data = 'client=fanyideskweb&mysticTime={}&product=webfanyi&key=fsdsogkndfokasodnaso'.format(
        localtime
    )
    sign = hashlib.md5(data.encode(encoding='utf-8')).hexdigest()
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
        'Referer': 'https://fanyi.youdao.com/index.html',
    }
    cookies = {
        'OUTFOX_SEARCH_USER_ID': '-2094880112@10.108.162.135',
        'OUTFOX_SEARCH_USER_ID_NCOO': '86107500.53660281',
    }
    url = 'https://dict.youdao.com/webtranslate'
    data = {
        'i': f'{source_text}',
        'from': 'auto',
        'to': '',
        'dictResult': 'true',
        'keyid': 'webfanyi',
        'sign': sign,
        'client': 'fanyideskweb',
        'product': 'webfanyi',
        'appVersion': '1.0.0',
        'vendor': 'web',
        'pointParam': 'client,mysticTime,product',
        'mysticTime': localtime,
        'keyfrom': 'fanyi.web',
    }
    response = requests.post(url=url, headers=headers, cookies=cookies, data=data).text
#     js_str = u"""
# const crypto = require("crypto");
# const o =
#   "ydsecret://query/key/B*RGygVywfNBwpmBaZg*WT7SIOUP2T0C9WHMZN39j^DAdaZhAnxvGcCY6VYFwnHl";
# const n =
#   "ydsecret://query/iv/C@lZe2YzHtZ2CYgaXKSVfsb7Y4QWHjITPPZ0nQp87fBeJ!Iv6v^6fvi2WN@bYpJ4";
# function datas(t) {
#   const a = Buffer.alloc(16, crypto.createHash("md5").update(o).digest()),
#     r = Buffer.alloc(16, crypto.createHash("md5").update(n).digest()),
#     i = crypto.createDecipheriv("aes-128-cbc", a, r);
#   let s = i.update(t, "base64", "utf-8");
#   return (s += i.final("utf-8")), s;
# }
#     """
#     # FIXME: windows下执行出错, linux正常?
#     signs = execjs.compile(js_str).call('datas', response)
#     text = json.loads(signs)
#     try:
#         return text['dictResult']['ce']['word']['trs'][0]['#text']
#     except:
#         return text['translateResult'][0][0]['tgt']

    return _decode(response)

def chinese_to_english(source_text):
    return translate(source_text)

def english_to_chinese(source_text):
    return translate(source_text)


if __name__ == '__main__':
    # print(translate("测试"))
    print(english_to_chinese('hello'))
    # print(chinese_to_english('测试'))
